package com.test.testCode.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

@RestController
public class UpLoadFile {

//    private static final String ACCESS_KEY_ID = "LTAIRtTZ63xrlVIm";
//    private static final String ACCESS_KEY_SECRET = "jSW9l9SYKc8FOYCNDDahG6nBlOMxyT";
//    private static final String ENDPOINT = "http://oss-cn-shenzhen.aliyuncs.com";
//    private static final String BUCKET_NAME = "black-hold";

    private static final String ACCESS_KEY_ID = "";
    private static final String ACCESS_KEY_SECRET = "";
    private static final String ENDPOINT = "http://oss-cn-shenzhen.aliyuncs.com";
    private static final String BUCKET_NAME = "black-hold";

    /**
     * 上传文件
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/upLoadFile")
    public String upLoadFile(@RequestParam("filepath") String filePath) throws IOException {
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 上传
        long time = new Date().getTime();
//        ossClient.putObject(BUCKET_NAME, "new/file1.txt", new FileInputStream(new File("d:\\test\\file.txt")));
        ossClient.putObject(BUCKET_NAME, "new/file1.txt", new FileInputStream(new File(filePath)));
        // 关闭client
        ossClient.shutdown();
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        String url = ossClient.generatePresignedUrl(BUCKET_NAME, "file1.txt", expiration).toString();
        return url;
    }

    /**
     * 下载文件到本地
     *
     * @throws IOException
     */
    @GetMapping("/downLoadFile")
    public void downLoadFile() throws IOException {
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        ossClient.getObject(new GetObjectRequest(BUCKET_NAME, "file1.txt"), new File("d://test.txt"));
        ossClient.shutdown();
    }
}
